package com.gome.boot.common.util;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

/**
 * HTTP请求工具类.
 *
 * @author baoxiufeng
 */
public class HttpUtils {

    /**
     * HttpClient客户端
     */
    private static final CloseableHttpClient client = HttpClients.createDefault();

    /**
     * POST请求处理.
     *
     * @param url 请求URL
     * @param params 请求参数
     * @return 请求结果
     * @throws IOException IO异常
     */
    public static String post(String url, String params) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
        CloseableHttpResponse response = client.execute(httpPost);
        return EntityUtils.toString(response.getEntity(), "UTF-8");
    }

    /**
     * GET请求处理.
     *
     * @param url 请求URL
     * @param params 请求参数
     * @return 请求结果
     * @throws IOException IO异常
     */
    public static String get(String url, List<NameValuePair> params) throws Exception {
        HttpGet httpGet = null;
        if (params == null || params.isEmpty()) {
            httpGet = new HttpGet(url);
        } else {
            httpGet = new HttpGet(new URIBuilder(url).addParameters(params).build());
        }
        httpGet.addHeader("Content-type", "application/json; charset=utf-8");
        httpGet.setHeader("Accept", "application/json");
        CloseableHttpResponse response = client.execute(httpGet);
        return EntityUtils.toString(response.getEntity(), "UTF-8");
    }

    /**
     * GET请求处理.
     *
     * @param url 请求URL
     * @param params 请求参数
     * @return 请求结果
     * @throws IOException IO异常
     */
    public static HttpResponse httpGet(String url, List<NameValuePair> params) throws Exception {
        HttpGet httpGet = null;
        if (params == null || params.isEmpty()) {
            httpGet = new HttpGet(url);
        } else {
            httpGet = new HttpGet(new URIBuilder(url).addParameters(params).build());
        }
        httpGet.addHeader("Content-type", "application/json; charset=utf-8");
        httpGet.setHeader("Accept", "application/json");
        return client.execute(httpGet);
    }
}
